package com.sky.AutoFillAspect;

import com.sky.anno.AutoFillAnno;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
//切面类
public class AutoFillAspect {
    //定义切入点
    @Pointcut("execution(* com.sky.mapper.*.* (..)) && @annotation(com.sky.anno.AutoFillAnno)")
    public void autoFillPointCut() {
    }

    @Before("autoFillPointCut()")
    public void autofill(JoinPoint joinPoint) {
        log.info("自动填充开始了..");
        //获取注解value，确认操作是insert还是update
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
        AutoFillAnno anno = signature.getMethod().getAnnotation(AutoFillAnno.class);//getMethod()获取被拦截的方法getAnnotation()获取注解对象
        OperationType value = anno.value();//获取操作类型
        //获取方法形参(约定第一个为employee)
        Object[] args = joinPoint.getArgs();
        Object arg = new Object();
        if (args == null || args.length == 0) {
            return;
        } else {
            arg = args[0];//获取参数对象
        }
        //准备插入或更新数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        try {
            //通过反射获取方法
            if (value == OperationType.INSERT) {
                //如果是INSERT方法就更新创建人,创建时间,修改人，修改时间
                Method setCreateTime = args.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);//方法名，方法参数类型
                Method setUpdateTime = args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreateUser = args.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateUser = args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                //调用方法插入数据
                setCreateTime.invoke(arg, now);
                setCreateUser.invoke(arg, currentId);
                setUpdateUser.invoke(arg, currentId);
                setUpdateTime.invoke(arg, now);
            } else {
                //如果是update方法就更新创建人和创建时间
                Method setUpdateUser = args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                Method setUpdateTime = args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                setUpdateUser.invoke(arg, currentId);
                setUpdateTime.invoke(arg, now);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
